<?php

namespace App\Services;

use App\Models\ElementModel;
use App\Models\FloorModel;
use App\Models\RoomModel;
use App\Traits\HelperTrait;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class RoomService extends BaseService
{
    use HelperTrait;

    protected $error_msg = '';

    /**
     * Notes: 获取单元和楼层列表
     * User: lstink
     * Date: 2021/2/4
     * Time: 10:48 上午
     * @param $where
     * @return mixed
     */
    public function getElementList($where, $param)
    {
        return RoomModel::whereHas('house', function ($query) use ($param) {
            //楼栋
            if (!empty($param['house_num'])) {
                $query->where('house_num', $param['house_num']);
            }
        })->whereHas('element', function ($query) use ($param) {
            //单元
            if (!empty($param['element_num'])) {
                $query->where('element_num', $param['element_num']);
            }
        })->whereHas('floor', function ($query) use ($param) {
            //楼层
            if (!empty($param['floor'])) {
                $query->where('floor', $param['floor']);
            }
        })->with(['community', 'house', 'element', 'floor'])->where($where)->where(function ($query) use ($param) {
            //小区
            if (!empty($param['c_id'])) {
                $query->where('c_id', $param['c_id']);
            }
            //房间号
            if (!empty($param['room'])) {
                $query->where('room', $param['room']);
            }
        })->paginate($param['per_page'] ?? 30);
    }

    public function addElement($data, $estate_id)
    {
        //验证数据
        $validator = Validator::make($data, [
            'community_id' => 'required',
            'h_id'         => 'required',
            'e_id'         => 'required',
            'room'         => 'required',
        ], [
            'community_id.required' => '请选择小区！',
            'h_id.required'         => '请选择楼号！',
            'e_id.required'         => '请选择单元号！',
            'room.required'         => '请填写房间号！',
        ]);
        if ($validator->fails()) {
            $this->error_msg = $validator->errors()->first();
            return false;
        }
        //处理楼层信息
        return $this->handleHouse($data, $estate_id);
    }

    /**
     * Notes: 处理楼栋数据
     * User: lstink
     * Date: 2021/2/4
     * Time: 10:00 上午
     * @param $data
     * @param $estate_id
     * @return mixed
     */
    protected function handleHouse($data, $estate_id)
    {
        $is_mul = [];
        if ($this->isMul($data['room'])) {
            $arr    = explode('-', $data['room']);
            $is_mul = array_filter($arr);
        }
        //开启事务
        DB::beginTransaction();
        try {
            //判断楼层是否存在--存在
            if (!empty($data['f_id'])) {
                //单楼层添加
                $this->addRoomData($data, $estate_id, $is_mul);
            } else {
                //所有楼层添加--查询对应单元的所有楼层
                $floor_all = (new HouseService)->getFloorListByElement($data['e_id']);
                if (empty($floor_all)) {
                    //不存在楼层数据
                    throw new \Exception('不存在楼层数据，请先添加楼层数据');
                }
                //遍历所有楼层--添加每个楼层的房间
                foreach ($floor_all as $item) {
                    $this->addRoomData($data, $estate_id, $is_mul, $item['floor']);
                }
            }
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();
            $this->error_msg = $e->getMessage() == '不存在楼层数据，请先添加楼层数据' ?? '存在已有房间号，请勿重复添加';
            return false;
        }
        return true;
    }

    /**
     * Notes: 判断是否为批量添加
     * User: lstink
     * Date: 2021/2/3
     * Time: 3:57 下午
     * @param $value
     * @return bool
     */
    protected function isMul($value)
    {
        if (strpos($value, '-') === false) {
            return false;
        }

        return true;
    }

    /**
     * Notes: 添加单个楼层的所有房间数据
     * User: lstink
     * Date: 2021/2/5
     * Time: 6:12 下午
     * @param $data
     * @param $estate_id
     * @param $arr
     * @param string $floor
     * @return array
     */
    protected function addRoomData($data, $estate_id, $arr, $floor = null)
    {
        //单楼层添加
        $room = [];
        if (!empty($arr)) {
            //批量添加
            for ($i = $arr[0]; $i <= $arr[1]; $i++) {
                $room[] = [
                    'estate_id' => $estate_id,
                    'c_id'      => $data['community_id'],
                    'h_id'      => $data['h_id'],
                    'e_id'      => $data['e_id'],
                    'f_id'      => $floor ?? $data['f_id'],
                    'room'      => $i,
                ];
            }
        } else {
            //如果是所有楼层
            if (!empty($floor)) {
                //遍历所有房间号
                $num = $floor * 100;
                for ($i = $num + 1; $i <= $data['room'] + $num; $i++) {
                    $room[] = [
                        'estate_id' => $estate_id,
                        'c_id'      => $data['community_id'],
                        'h_id'      => $data['h_id'],
                        'e_id'      => $data['e_id'],
                        'f_id'      => $floor ?? $data['f_id'],
                        'room'      => $i,
                    ];
                }
            } else {
                //单个添加
                $room[] = [
                    'estate_id' => $estate_id,
                    'c_id'      => $data['community_id'],
                    'h_id'      => $data['h_id'],
                    'e_id'      => $data['e_id'],
                    'f_id'      => $floor ?? $data['f_id'],
                    'room'      => $data['room'],
                ];
            }
        }
        return RoomModel::insert($room);
    }

    /**
     * Notes: 获取错误信息
     * User: lstink
     * Date: 2021/2/4
     * Time: 10:02 上午
     * @return string
     */
    public function getMessage()
    {
        return $this->error_msg;
    }
}
